package spirit.io.bio;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * bio 服务端
 */
public class BioServer {

    /**
     * 服务端网络io 的封装对象
     */
    ServerSocket serverSocket;

    public BioServer(int port) {
        try {
            serverSocket = new ServerSocket(port);
            System.out.println("BIO server 已经启动，监听" + port + "端口， 等待接收数据......");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void listen() {
        while (true) {
            try {
                // 等待客户端来连接
                Socket client = serverSocket.accept();
                // 对方数据发送过来了
                InputStream is = client.getInputStream();
                byte[] bytes = new byte[1024];
                int len = is.read(bytes);
                if (len > 0) {
                    String msg = new String(bytes, 0, len);
                    System.out.println("接收到来自客户端的新信息： " + msg);
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    public static void main(String[] args) {
        new BioServer(8080).listen();
    }
}
